package com.yonyou.tj.controller;

import com.alibaba.fastjson.JSONObject;
import com.yonyou.iuap.context.InvocationInfoProxy;
import com.yonyou.tj.service.SignService;
import com.yonyou.ucf.mdd.ext.base.BaseController;
import com.yonyou.ucf.mdd.ext.util.ResultMessage;
import lombok.extern.slf4j.Slf4j;
import org.imeta.core.rest.AuthSdkUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import yonyou.bpm.rest.BpmRests;
import yonyou.bpm.rest.RuntimeService;
import yonyou.bpm.rest.TaskService;
import yonyou.bpm.rest.exception.RestException;
import yonyou.bpm.rest.impl.DefaultRunTimeService;
import yonyou.bpm.rest.param.BaseParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import javax.servlet.http.Cookie;
import java.net.URLEncoder;

@Slf4j
@RestController
@RequestMapping("/sign")
public class SignResultController  extends BaseController {

    @Autowired
    public SignService signService;

//    @Autowired
//    private RestTemplate restTemplate;

    /**
     *
     * @param params
     * @param request
     * @param response
     */
    @PostMapping("/getSignResultByInstId")
    public void getSignResultByInstId(@RequestBody Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
        try {
            String res = signService.getSignResultByInstId(params);
            Map<String,String> result = new HashMap<>();
            result.put("signResult", res);
            renderJson(response, ResultMessage.data(result));
        } catch (Exception e) {
            e.printStackTrace();
            renderJson(response, ResultMessage.error(e.getMessage()));
        }
    }

    /**
     */
    @GetMapping("/approveBill")
    public void approveBill(String tenantId,
                            String serverUrl,
                            String domainUrl,
                            String sourceCode,
                            String taskId, String userId, HttpServletRequest request, HttpServletResponse response) throws RestException {
        try {
            BaseParam baseParam = new BaseParam();
            baseParam.setServer(serverUrl); // yms专属⽅式：中台域名/iuap-apcom-workflownew/ubpm-webrest
            baseParam.setRestServerVersion("REST_SERVICE_1.0.0");
            baseParam.addHeader("restservice", "rest_sdk_1.0"); //默认为：rest_sdk_1.0
            baseParam.setTenantLimitId(tenantId);//友户通租户id ycqd3s4c oiwnv4es
            baseParam.setSource(sourceCode); // 业务来源subid，客开通常设置为应⽤引擎编码，应⽤引擎需要对接审批流
            baseParam.setYhtAccessToken(InvocationInfoProxy.getYhtAccessToken()); // 流程校验使⽤
            TaskService taskService = BpmRests.getBpmRest(baseParam).getTaskService();
            Object completeResult = taskService.complete(taskId);
            renderJson(response, ResultMessage.data(completeResult));
        } catch (Exception e) {
            e.printStackTrace();
            renderJson(response, ResultMessage.error(e.getMessage()));
        }
    }

//    private String getYhtAccessToken(String userId, String domainUrl, String tenantId) throws Exception{
//        String jsonString = domainUrl+"/cas/exclusive/genLoginTokenByUserIdLimitIp?userId="+userId;
//        // System.out.println(jsonString);
//        JSONObject obj = JSONObject.parseObject(jsonString);
//        String token = (String) obj.get("token");
//
//        //yht登录
//        String yhtLogin = domainUrl + "/cas/login?token=" + token;
//
//        String urlq = domainUrl + "/login?service=";
//        yhtLogin += "&service=" + URLEncoder.encode(urlq, "UTF-8");
//        Connection.Response res2 = Jsoup.connect(yhtLogin)
//                .ignoreContentType(true)
//                .execute();
//        Map<String, String> cookies = res2.cookies();
//        StringBuilder tmpcookies = new StringBuilder();
//
//        for (String key : cookies.keySet()) {
//            String value = cookies.get(key);
//            tmpcookies.append(key).append("=").append(value).append(";");
//            Cookie cookie = new Cookie(key, value);
//            cookie.setPath("/");
//            cookie.setMaxAge(60 * 60 * 24 * 10);
//            // response.addCookie(cookie);
//        }
//        Cookie userIdCookie = new Cookie("yonyou_uid", userId);
//        userIdCookie.setPath("/");
//        userIdCookie.setMaxAge(60 * 60 * 24 * 10);
//        // response.addCookie(userIdCookie);
//        String workbenchLogUrl = domainUrl + "/login?tenantId=" + tenantId;
//        Document document3 = Jsoup.connect(workbenchLogUrl)
//                .ignoreContentType(true)
//                .header("Cookie", tmpcookies.toString())
//                .get();
//        String ansUrl = document3.toString().split("window.location.href = ")[1].split(";")[0].replace("\"", "");
//
//        Connection.Response res3 = Jsoup.connect(ansUrl)
//                .ignoreContentType(true)
//                .execute();
//
//        Map<String, String> ansCookies = res3.cookies();
//        // System.out.println(ansCookies);
//        return ansCookies.get("yht_access_token");  // 不是所有的用户都有的
//
//    }
//
//    public void approveBill1(String tenantId,
//                            String serverUrl,
//                            String sourceCode,
//                            String taskId, String yhttoken) throws RestException {
//            BaseParam baseParam = new BaseParam();
//            baseParam.setServer(serverUrl); // yms专属⽅式：中台域名/iuap-apcom-workflownew/ubpm-webrest
//            baseParam.setRestServerVersion("REST_SERVICE_1.0.0");
//            baseParam.addHeader("restservice", "rest_sdk_1.0"); //默认为：rest_sdk_1.0
//            baseParam.setTenantLimitId(tenantId);//友户通租户id ycqd3s4c oiwnv4es
//            baseParam.setSource(sourceCode); // 业务来源subid，客开通常设置为应⽤引擎编码，应⽤引擎需要对接审批流
//            baseParam.setYhtAccessToken(yhttoken); // 流程校验使⽤
//            TaskService taskService = BpmRests.getBpmRest(baseParam).getTaskService();
//            Object completeResult = taskService.complete(taskId);
//    }

    /**
     *
     * @param params
     * @param request
     * @param response
     */
    @PostMapping("/queryUserInfoByRole")
    public void queryUserInfoByRole(@RequestBody Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
        log.error("流程外部变量计算=====:{}", params);
        try {
            Map<String, Object> result = new HashMap<>();
            result.put("status", "200");
            result.put("message", "外部变量计算完成");
            result.put("queryUserInfoByRole", "219cb864-519c-41fb-8fd0-5a51e903220a,1850e40b-f4ac-471d-abc7-b4a7f65ba753");
            result.put("boolVar1", true);
            renderJson(response, new JSONObject(result).toJSONString());
        } catch (Exception e) {
            e.printStackTrace();
            renderJson(response, ResultMessage.error(e.getMessage()));
        }
    }


    /**
     *
     * @param request
     * @param response
     */
    @GetMapping("/getHighlightsProcessInstance")
    public void getHighlightsProcessInstance(String tenantId,
                                             String serverUrl,
                                             String domainUrl,
                                             String sourceCode,
                                             String instId, String userId, HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> result = new HashMap<>();
            BaseParam baseParam = new BaseParam();
            baseParam.setServer(serverUrl); // yms专属⽅式：中台域名/iuap-apcom-workflownew/ubpm-webrest
            baseParam.setRestServerVersion("REST_SERVICE_1.0.0");
            baseParam.addHeader("restservice", "rest_sdk_1.0"); //默认为：rest_sdk_1.0
            baseParam.setTenantLimitId(tenantId);//友户通租户id ycqd3s4c oiwnv4es
            baseParam.setSource(sourceCode); // 业务来源subid，客开通常设置为应⽤引擎编码，应⽤引擎需要对接审批流
            baseParam.setYhtAccessToken(InvocationInfoProxy.getYhtAccessToken()); // 流程校验使⽤
            RuntimeService runtimeService = BpmRests.getBpmRest(baseParam).getRuntimeService();
            Object highlightsProcessInstance = runtimeService.getHighlightsProcessInstance(instId);
            renderJson(response, ResultMessage.data(highlightsProcessInstance));
        } catch (Exception e) {
            e.printStackTrace();
            renderJson(response, ResultMessage.error(e.getMessage()));
        }
    }

    @GetMapping("/getCurrentApproveInfo")
    public void getCurrentApproveInfo(String businessKey,
                                      String tenantAppSource,
                                      String mainURL,
                                      String yht_access_token, HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> param = new HashMap<>();
            param.put("businessKey", businessKey);
            Map<String, String> headers = new HashMap<>();
            headers.put("businessKey", businessKey);
            headers.put("tenantAppSource", tenantAppSource);
            headers.put("yht_access_token", yht_access_token);
            String post = AuthSdkUtils.post(mainURL + "/iuap-apcom-workflownew/approve-component/api/v1/approve/load", new JSONObject(param).toJSONString(), headers);
            renderJson(response, post);
        } catch (Exception e) {
            e.printStackTrace();
            renderJson(response, ResultMessage.error(e.getMessage()));
        }
    }

    @GetMapping("/unsubmit")
    public void unsubmit(String busiObj,
                                      String billid,
                                      String mainURL,
                                      String yht_access_token, String domainKey, HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> param = new HashMap<>();
            param.put("billnum", busiObj);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", billid);
            param.put("data", jsonObject.toJSONString());

            Map<String, String> headers = new HashMap<>();
            headers.put("yht_access_token", yht_access_token);
            headers.put("Domain-Key", domainKey);
            String post = AuthSdkUtils.post(mainURL + "/" +domainKey+ "-be/bill/unsubmit?busiObj="+busiObj, new JSONObject(param).toJSONString(), headers);
            renderJson(response, post);
        } catch (Exception e) {
            e.printStackTrace();
            renderJson(response, ResultMessage.error(e.getMessage()));
        }
    }

//    /**
//     *
//     * @param params
//     * @param request
//     * @param response
//     */
//    @PostMapping("/getActsimesByParams")
//    public void getActsimesByParams(@RequestBody Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
//        try {
//            String res = signService.getActsimesByParams(params);
//            Map<String,String> result = new HashMap<>();
//            result.put("signResult", res);
//            renderJson(response, ResultMessage.data(result));
//        } catch (Exception e) {
//            e.printStackTrace();
//            renderJson(response, ResultMessage.error(e.getMessage()));
//        }
//    }
}
